<script setup lang="ts">
import itemTypeProductPicker from './item-type-product-picker.vue';
import { reactive, ref, onMounted } from 'vue';
import { eventCenter, getCurrentInstance } from '@tarojs/taro';
import { ItemTypeDto } from '../index';
const props = defineProps<{
  item: ItemTypeDto;
  productList: IbFpProductApi.Dto[];
}>();

const state = reactive<{
  productNames: string[];
  quantity: string;
  productSpecNames: string[];
}>({
  productNames: [],
  quantity: '',
  productSpecNames: [],
});
//如果已经填写过数量保存
if (props.item.quantity) {
  state.quantity = props.item.quantity.toString();
}

//初始化productNames
props.productList.forEach((item) => state.productNames.push(item.productName || ''));
const selectProductSpecRef = ref();

if (props.item.productName) {
  selectProductName(props.item.productName);
}
/**
 * 选择产品名称 生成 产品规格列表
 * @param name 选择产品名称
 */
function selectProductName(name: string) {
  //选择不同产品清楚清楚之前产品规格
  if (props.item.productName !== name) {
    props.item.productSpecName = '';
    selectProductSpecRef.value.state.radioVal = '';
  }
  props.item.productName = name;
  const product = props.productList?.find((item) => item.productName === name);
  if (!product) {
    return;
  }
  props.item.productId = product.id;
  props.item.unitPrice = product.unitPrice;
  state.productSpecNames.splice(0, state.productSpecNames.length);
  state.productSpecNames.push(...(product.productSpecName?.trim().split(',') || []));
}

function selectProductSpecName(name: string) {
  props.item.productSpecName = name;
}

function inputChange() {
  props.item.quantity = Number(state.quantity);
}
onMounted(() => {
  eventCenter.on(getCurrentInstance().router?.onShow as string, () => {
    //清理数据，当成功页面返回的时候，显示初始状态
    state.quantity = '';
  });
});
</script>
<template>
  <nut-form>
    <nut-form-item label="物品品类" required>
      <item-type-product-picker
        :selected-value="item.productName"
        :names="state.productNames"
        @on-change="selectProductName"
        placeholder="请选择物品品类"
      />
    </nut-form-item>
    <nut-form-item label="规格" required>
      <item-type-product-picker
        :selected-value="item.productSpecName"
        ref="selectProductSpecRef"
        :names="state.productSpecNames"
        @on-change="selectProductSpecName"
        placeholder="请选择物品规格"
      />
    </nut-form-item>
    <nut-form-item label="数量" required>
      <nut-input
        @update:model-value="inputChange"
        v-model="state.quantity"
        placeholder="请填写"
        type="number"
        input-align="right"
        :border="false"
      />
    </nut-form-item>
  </nut-form>
</template>
<style lang="scss">
.item-type-form-item {
  display: flex;
  align-items: center;
  color: #999;
  font-size: 30px;
  &__left {
    flex: 1;
  }
  .nut-input {
    &--border {
      border-bottom: none;
    }
  }
}
</style>
